import java.util.ArrayList;

public class MonteCarloAgent extends Agent{

	public final int NUMBER_SAMPLES = 5000;


	@Override
	public void evaluateProbabilities()
	{
		ArrayList<Card> fullCards = getFullCards();
		Hand best = Hand.getBestHand(fullCards);
		if (Simulator.DEBUG)
		System.out.println("Best hand is: " + best.toString());
		simulate(table);
	}
	
	
	@Override
	public Action takeTurn()
	{
		printCards();
		
		ArrayList<Card> fullCards = getFullCards();
		Hand best = Hand.getBestHand(fullCards);
		double value = 0;
		double[] estimates = getEstimates(table);
		for (int i = 0; i < 9; i++)
		{
			value += Math.pow(i+1, 2)/2 * estimates[i];
		}
		//System.out.println("value : "+value);
		int handValue = (int)value;
		
		
		
		int tableBet = table.getRoundBet();
		if (Math.random() * tableBet > handValue * (7 - getFullCards().size()+ 1))
			return Action.foldAction();
		else if (tableBet >= handValue)
			return Action.callAction();
		else
		{
			int raiseAmt = table.getMaxBet() + handValue - tableBet;
			return Action.raiseAction(raiseAmt);
		}
		
			
	}
	
	public double[] getEstimates(Table table)
	{
		Integer[] handArray = new Integer[9];
		for (int i = 0; i < 9; i++)
			handArray[i] = 0;
		for (int i = 0; i < NUMBER_SAMPLES; i++)
		{
			ArrayList<Card> deck = table.getCards(this);
			ArrayList<Card> potentialHand = cloneCards(cards);
			potentialHand.addAll(cloneCards(table.visibleCards));

			for (int j = potentialHand.size(); j < 7; j++)
				potentialHand.add(deck.remove(0));

			Hand best = Hand.getBestHand(potentialHand);
			handArray[best.getType()]++;
		}
		
		double[] estimates = new double[9];
		for (int i = 0; i < 9; i++)
		estimates[i] = ((double)handArray[i])/NUMBER_SAMPLES;
		
		
	/*	System.out.println("Samples Results:");
		String results = "";
		for (int i = 0; i<9; i++ )
			results += ""+estimates[i]+", ";
		System.out.println(results);*/
		return estimates;

	}

	public void simulate(Table table)
	{
		Integer[] handArray = new Integer[9];
		for (int i = 0; i < 9; i++)
			handArray[i] = 0;
		for (int i = 0; i < NUMBER_SAMPLES; i++)
		{
			ArrayList<Card> deck = table.getCards(this);
			ArrayList<Card> potentialHand = cloneCards(cards);
			potentialHand.addAll(cloneCards(table.visibleCards));

			for (int j = potentialHand.size(); j < 7; j++)
				potentialHand.add(deck.remove(0));

			Hand best = Hand.getBestHand(potentialHand);
			handArray[best.getType()]++;
		}
		
		System.out.println("Samples Results:");
		String results = "";
		for (int i = 0; i<9; i++ )
			results += ""+handArray[i]+", ";

		System.out.println(results);
	}

	public ArrayList<Card> cloneCards(ArrayList<Card> hand)
	{
		ArrayList<Card> cloneHand = new ArrayList<Card>();
		for (Card c:hand)
		{
			cloneHand.add(c.clone());
		}
		return cloneHand;
	}

}
